﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using AvaloniaApplicationDemo.IServices;
using AvaloniaApplicationDemo.Models;
using AvaloniaApplicationDemo.Util;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SukiUI.Dialogs;

namespace AvaloniaApplicationDemo.ViewModels;

public partial class ModbusConfigViewModel : ObservableObject
{
    #region 依赖注入部分

    private readonly IConfigCSVManager _configCsvManager;
    public ISukiDialogManager DialogManager { get; }

    public DeviceModel DeviceModel { get; set; }

    #endregion

    /// <summary>
    /// 设备数据映射表
    /// </summary>
    [ObservableProperty] private Dictionary<ushort, string> _registerMappings = new();


    public ModbusConfigViewModel(IConfigCSVManager configCsvManager, ISukiDialogManager dialogManager)
    {
        _configCsvManager = configCsvManager;
        DialogManager = dialogManager;
        DeviceModel = new DeviceModel();
    }

    [RelayCommand]
    private async Task ExportConfigTemplateAsync()
    {
        try
        {
            // 获取主窗口的TopLevel以访问StorageProvider
            var topLevel = Avalonia.Application.Current?.ApplicationLifetime is
                Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop
                ? TopLevel.GetTopLevel(desktop.MainWindow)
                : null;

            if (topLevel == null)
            {
                DialogManager.CreateDialog()
                    .WithContent("无法获取应用程序主窗口，请重试")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                AppLogger.Information("导出配置模板失败：无法获取主窗口");
                return;
            }

            // 创建文件保存选项
            var filePickerOptions = new FilePickerSaveOptions
            {
                Title = "导出配置模板",
                SuggestedFileName = $"Modbus_Config_Template_{DateTime.Now:yyyyMMdd_HHmmss}.csv",
                SuggestedStartLocation = await topLevel.StorageProvider.TryGetFolderFromPathAsync(
                    Environment.GetFolderPath(Environment.SpecialFolder.Desktop)),
                FileTypeChoices = new List<FilePickerFileType>
                {
                    new("CSV文件") { Patterns = ["*.csv"] }
                }
            };

            // 显示文件保存对话框
            var result = await topLevel.StorageProvider.SaveFilePickerAsync(filePickerOptions);
            if (result == null)
            {
                // 用户取消选择
                AppLogger.Information("用户取消导出配置模板");
                return;
            }

            // 获取文件路径
            var filePath = result.Path.LocalPath;

            // 调用服务方法导出模板
            var success = _configCsvManager.ExportConfigTemplate(filePath, RegisterMappings);

            // 显示导出结果
            if (success)
            {
                DialogManager.CreateDialog()
                    .WithContent($"配置模板导出成功！\n文件保存位置：{filePath}")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                AppLogger.Information("配置模板导出成功，文件路径：{FilePath}", filePath);
            }
            else
            {
                DialogManager.CreateDialog()
                    .WithContent("配置模板导出失败，请检查文件路径是否有效")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                AppLogger.Warning("配置模板导出失败，文件路径：{FilePath}", filePath);
            }
        }
        catch (Exception ex)
        {
            DialogManager.CreateDialog()
                .WithContent($"导出过程中发生错误：{ex.Message}")
                .WithActionButton("确定", _ => { }, true)
                .TryShow();
            AppLogger.Error(ex, "导出配置模板时发生异常");
        }
    }

    [RelayCommand]
    private async Task ImportConfigFileAsync()
    {
        try
        {
            // 创建文件选择对话框
            var dialog = new OpenFileDialog
            {
                Title = "选择配置文件",
                Filters = new List<FileDialogFilter>
                {
                    new() { Name = "CSV文件", Extensions = { "csv" } },
                    new() { Name = "所有文件", Extensions = { "*" } }
                },
                AllowMultiple = false
            };

            // 显示对话框并获取选择的文件路径
            var mainWindow =
                Avalonia.Application.Current?.ApplicationLifetime is
                    Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop
                    ? desktop.MainWindow
                    : null;

            if (mainWindow == null)
            {
                DialogManager.CreateDialog()
                    .WithContent("无法获取主窗口，请重试")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                AppLogger.Information("导入配置文件失败：无法获取主窗口");
                return;
            }

            var result = await dialog.ShowAsync(mainWindow);
            if (result == null || result.Length == 0)
            {
                // 用户取消选择
                DialogManager.CreateDialog()
                    .WithContent("导入配置文件取消")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                return;
            }

            var filePath = result[0];

            // // 显示导入中提示
            // DialogManager.CreateDialog()
            //     .WithContent("正在导入配置文件，请稍候...")
            //     .WithActionButton("确定", _ => { }, true)
            //     .TryShow();

            // 调用服务方法导入配置
            var success = _configCsvManager.ImportRegisterMappingsFromCsv(filePath, DeviceModel);

            // 显示导入结果
            if (success)
            {
                DialogManager.CreateDialog()
                    .WithContent($"配置文件导入成功，共导入 {DeviceModel.RegisterMappings.Count} 个寄存器映射")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                AppLogger.Information("配置文件导入成功，文件路径：{FilePath}，导入数量：{Count}", filePath,
                    DeviceModel.RegisterMappings.Count);
                RegisterMappings = DeviceModel.RegisterMappings;
            }
            else
            {
                DialogManager.CreateDialog()
                    .WithContent("配置文件导入失败，请检查文件格式是否正确")
                    .WithActionButton("确定", _ => { }, true)
                    .TryShow();
                AppLogger.Warning("配置文件导入失败，文件路径：{FilePath}", filePath);
            }
        }
        catch (Exception ex)
        {
            DialogManager.CreateDialog()
                .WithContent($"导入过程中发生错误：{ex.Message}")
                .WithActionButton("确定", _ => { }, true)
                .TryShow();
            AppLogger.Error(ex, "导入配置文件时发生异常");
        }
    }
}